/*
 * @Author: your name
 * @Date: 2020-10-16 17:07:41
 * @LastEditTime: 2020-11-02 15:13:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /Project/node/services/userService.js
 */
/**
 * 登录
 */
const boom = require('boom');
const {querySql, queryOne, guard} = require('../utils')
const {validationResult } = require('express-validator');


function onLogin(req, res, next) {
  
  guard(req,next, () => {
    console.log("登录信息22:",req.body);
    let { phone,userType} = req.body;

    switch (userType) {
      case 0: {
        //用户登录
        const onLoginSql = `create table if not exists User(
          userId INT NOT NULL,                
          phone VARCHAR(255) NOT NULL, 
          token VARCHAR(255) NOT NULL ,
          userType INT NOT NULL, 
          createTime DATETIME(3) NULL DEFAULT CURRENT_TIMESTAMP(3) ,  
          PRIMARY KEY (userId) )`
        querySql(onLoginSql).then((response) => {
          if (response) {
            //检查是否是新用户
            const checkSql = `select * from myDB.User where phone=${phone}`
            queryOne(checkSql).then((item) => {
              if (item) {
                //老用户
                const userIdSql = `select * from myDB.User where phone=${phone}`
                querySql(userIdSql).then((result) => {
                  res.json({ code: 200, data: result[0],message:'登录成功'})
                })
              } else {
                //新用户  这里随机分配一个userId
                let userId = () => {
                    var code = '';
                    for (let i = 0; i < 9; i++) {
                        const num = Math.floor(Math.random() * 10);
                        code += num;
                    }
                    return code;
                }
                //插入新的用户
                const Id = userId()
                let insertSql = `INSERT INTO myDB.User 
                (userId, phone, token,userType) 
                VALUES (${Id}, ${phone}, ${'123456'},${userType})`
                querySql(insertSql).then((response) => {
                    res.json({ code: 200, data: {userId:Id,userType},message:'登录成功'})
                }).catch((err) => console.log("错误:",err))
              }
            })
          }
        })

      } break;
        case 1: {
          //商家登录
          const sql = `select * from myDB.Business where phone=${phone}`
          querySql(sql).then((result) => {
            res.json({ code: 200, data: result[0],message:'登录成功'})
          }).catch((err) => console.log("错误:",err))
        } break;
        case 2: {
          //骑手登录

        } break;
      default:
        break;
    }
  });
}
//商家注册
function registerBusiness(req, res, next) {
  guard(req,next, () => {
    //建表  商家
    const businessSql = `create table if not exists Business (
        businessId INT NOT NULL AUTO_INCREMENT COMMENT '商家id',  
        phone VARCHAR(255) NOT NULL COMMENT '商家手机号', 
        userType INT NOT NULL  DEFAULT 1 COMMENT '用户类型(默认值为1:商家)',
        BusinessName VARCHAR(255) NOT NULL COMMENT '商家名称', 
        BusinessLocation VARCHAR(255) NOT NULL COMMENT '商家位置信息',
        longitude VARCHAR(255) NOT NULL COMMENT '商家经度',
        latitude VARCHAR(255) NOT NULL COMMENT '商家纬度',
        createTime DATETIME(3) NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '商家插入时间，也就是下单时间', 
        PRIMARY KEY (businessId) )`
        
    querySql(businessSql).then((response) => {        
        if (response) {
            //插入一条新的订单数据
            let { 
              phone, 
              BusinessName,
              BusinessLocation,
              longitude, 
              latitude 
            } = req.body;

            //检查重复性
            const checkSql = `select * from myDB.Business where phone=${phone}`
            queryOne(checkSql).then((result) => {
              if (result) {
                //已经注册过
                res.json({code:300, msg:'此手机号已经注册过商家'})

              } else {
                //没有注册过,开始注册
                let insertSql = `INSERT INTO myDB.Business 
                (phone, BusinessName, BusinessLocation, longitude, latitude) VALUES 
                ("${phone}", "${BusinessName}","${BusinessLocation}",${longitude},${latitude})`

                querySql(insertSql).then((result) =>{
                    res.json({code:200,data:{orderId:result.insertId},msg:'注册成功'})
                    //插入成功以后 查询这条的订单id返回过去
                })
              }
            })
        }
        })
      })
}

module.exports = {
    onLogin,
    registerBusiness
}